package com.beiing.tianshuai.tianshuai.mine.ui.fragment;


import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.OrderCommentImageAdapter;
import com.beiing.tianshuai.tianshuai.adapter.PopupWindowSelectedAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.PopupWindowListBean;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelper;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelperCallback;
import com.beiing.tianshuai.tianshuai.mine.presenter.OrderApplyAfterSalePresenter;
import com.beiing.tianshuai.tianshuai.mine.ui.OrderApplyAfterSaleActivity;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileBatchCallback;
import com.zxy.tiny.callback.FileCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.beiing.tianshuai.tianshuai.mine.ui.FeedBackActivity.PERMISSIONS_REQUEST_READ_CONTACTS;

/**
 * A simple {@link Fragment} subclass.
 * 换货Fragment
 */
public class OrderExchangeGoodsFragment extends BaseFragment {

    /**
     * 换货原因
     */
    @BindView(R.id.tv_exchange_goods_reason_return)
    TextView tvExchangeReasonReturn;
    /**
     * 换货说明
     */
    @BindView(R.id.et_exchange_goods_explain)
    EditText etExchangeGoodsExplain;
    /**
     * 换货凭证图片列表
     */
    @BindView(R.id.rv_exchange_goods_voucher_photo)
    RecyclerView rvExchangeGoodsVoucherPhoto;
    /**
     * 提交按钮
     */
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    /**
     * 换货原因布局
     */
    @BindView(R.id.rl_exchange_goods_because)
    RelativeLayout rlExchangeGoodsBecause;

    /**
     * 退货原因popup
     */
    private EasyPopup mChooseExchangeReasonReceivedPopup;

    private static final String TAG = "OrderExchangeGoodsFragment";

    /**
     * 订单id
     */
    private String mOrderId;

    /**
     * 图片列表适配器
     */
    private OrderCommentImageAdapter mAdapter;

    private OrderApplyAfterSalePresenter mPresenter;

    /**
     * 创建一个新的fragment对象
     *
     * @return fragment
     */
    public static OrderExchangeGoodsFragment getInstance(String ordersId) {
        OrderExchangeGoodsFragment fragment = new OrderExchangeGoodsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("ordersId", ordersId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_order_exchang_goods;
    }

    @Override
    protected void init(View convertView) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mPresenter = ((OrderApplyAfterSaleActivity) mContext).getPresenter();
            mOrderId = arguments.getString("ordersId");
        }

        initRecyclerView();
        initListener();
    }

    private void initListener() {
        rlExchangeGoodsBecause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = "换货原因";
                String[] mRefundReasonsNotReceivedGoods = {"质量问题", "包裹少货/损坏/污渍",
                        "颜色/款式/型号不符", "卖家发错货", "假冒产品", "其他"};
                showGoodsStatePopupWindow(mChooseExchangeReasonReceivedPopup, mRefundReasonsNotReceivedGoods, title);
            }
        });
        // 图片点击事件
        mAdapter.setOnItemClickListener(new OrderCommentImageAdapter.OnItemClickListener() {
            @Override
            public void onImageClickListener(View view, int position) {
                int size = mAdapter.getList().size();
                if (size < 5 && position == size) {
                    checkSelfPermission();
                } else {
                    updateImage(position);
                }
            }

            @Override
            public void onImageDeleteClickListener(View view, int position) {
                mAdapter.removeData(position);
                int size = mAdapter.getList().size();
                LogUtils.i(mAdapter.getList().toString(), TAG);
                //既没有选择图片，也没有添加评论
                if (size == 0 && TextUtils.isEmpty(etExchangeGoodsExplain.getText())) {
                    showShortText("没有输入");
                }
            }
        });
        //提交按钮
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals(tvExchangeReasonReturn.getText().toString(), "请选择")) {
                    showShortText("请选择换货原因");
                    return;
                }
                //退货状态
                String goodsState = "换货没有货物状态";
                //退货原因
                String returnReason = tvExchangeReasonReturn.getText().toString();
                //退货类型
                String returnType = "退货退款";
                //退货说明
                String explain = etExchangeGoodsExplain.getText().toString();
                // 获取图片路径
                List<String> imgPaths = mAdapter.getList();

                mPresenter.postOrderApplyAfterSale(mOrderId, goodsState, returnReason, explain, returnType, imgPaths);

                //getActivity().finish();
            }
        });
    }

    /**
     * 判断popup是否有数据
     *
     * @param mList 数据
     * @param title 标题
     */
    private void showGoodsStatePopupWindow(EasyPopup mPopup, String[] mList, String title) {
        if (mPopup == null) {
            initGoodsStatePopupWindow(mPopup, mList, title);
        }
        mChooseExchangeReasonReceivedPopup.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);
        //showShortText("视图"+mPopup);
    }

    /**
     * 创建popup
     *
     * @param mList
     * @param title
     */
    private void initGoodsStatePopupWindow(EasyPopup mPopup, String[] mList, final String title) {
        //获取Activity根视图
        mChooseExchangeReasonReceivedPopup = mPopup;
        mChooseExchangeReasonReceivedPopup = new EasyPopup(getActivity());
        RelativeLayout activityRootView = ((OrderApplyAfterSaleActivity) mContext).getRlRootView();
        mChooseExchangeReasonReceivedPopup.setContentView(R.layout.popwin_goods_state, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setAnimationStyle(R.style.AnimBottom)
                .setFocusAndOutsideEnable(true)
                .setBackgroundDimEnable(true)
                .setDimValue(0.4f)
                .setDimColor(Color.BLACK)
                .setDimView(activityRootView)
                .createPopup();
        //初始化视图
        View contentView = mChooseExchangeReasonReceivedPopup.getContentView();

        TextView tvTitle = contentView.findViewById(R.id.tv_popup_title);
        TextView tvPopupSure = contentView.findViewById(R.id.tv_popup_btn_bottom);
        ImageButton ibPopupClose = contentView.findViewById(R.id.ib_popup_close);
        RecyclerView rlPopupSelected = contentView.findViewById(R.id.rv_popup_list_selected);

        tvTitle.setText(title);

        //创建LinearLayoutManager 对象
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        //设置RecyclerView 布局
        rlPopupSelected.setLayoutManager(mLayoutManager);
        rlPopupSelected.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0),
                ContextCompat.getColor(mContext, R.color.white)));

        //创建适配器
        final PopupWindowSelectedAdapter adapter = new PopupWindowSelectedAdapter(mContext);
        //加载数据到适配器
        List<PopupWindowListBean> list = new ArrayList<>();
        for (String mRefundReason : mList) {
            PopupWindowListBean popupWindowListBean = new PopupWindowListBean();
            popupWindowListBean.setItemText(mRefundReason);
            popupWindowListBean.setSelected(false);
            list.add(popupWindowListBean);
        }
        adapter.appendData(list);
        rlPopupSelected.setAdapter(adapter);

        final EasyPopup finalPopup = mChooseExchangeReasonReceivedPopup;
        tvPopupSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<PopupWindowListBean> list = adapter.getList();

                for (PopupWindowListBean listBean : list) {
                    if (listBean.isSelected()) {   //如果数据被选中
                        //showShortText("数据" + listBean.getItemText());

                        tvExchangeReasonReturn.setText(listBean.getItemText());
                        finalPopup.dismiss();

                    }
                }
            }
        });
        ibPopupClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finalPopup.dismiss();
            }
        });
        adapter.setOnItemClickListener(new PopupWindowSelectedAdapter.OnItemClickListener() {
            @Override
            public void onItemSelected(int position, PopupWindowListBean bean) {
                List<PopupWindowListBean> list = adapter.getList();
                // 找到当前默认的选项，设置它的选择状态为false
                for (PopupWindowListBean listBean : list) {
                    if (listBean.isSelected()) {
                        listBean.setSelected(false);
                        break;
                    }
                }
                // 设置当前用户选择的item，设置他的选择状态为true
                list.get(position).setSelected(true);
                adapter.notifyDataSetChanged();
            }
        });
    }

    //配置图片recyclerView
    private void initRecyclerView() {
        mAdapter = new OrderCommentImageAdapter(mContext);
        rvExchangeGoodsVoucherPhoto.setAdapter(mAdapter);
        //每行几个item,
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);
        /*
         *  设置SpanSizeLookup，它将决定view会横跨多少列。这个方法是为RecyclerView添加Header和Footer的关键。
         *  当判断position指向的View为Header或者Footer时候，返回总列数 lm.getSpanCount() ,即可让其独占一行。
         */
        rvExchangeGoodsVoucherPhoto.setNestedScrollingEnabled(false);
        rvExchangeGoodsVoucherPhoto.setLayoutManager(gridLayoutManager);
        //绘制item间的分割线，
        rvExchangeGoodsVoucherPhoto.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(10, 10, 10, 10);
            }
        });
        rvExchangeGoodsVoucherPhoto.setItemAnimator(new DefaultItemAnimator());

        // 设置ItemTouchListener
        DefaultItemTouchHelper defaultItemTouchHelper = new DefaultItemTouchHelper(mOnItemTouchCallbackListener);
        defaultItemTouchHelper.attachToRecyclerView(rvExchangeGoodsVoucherPhoto);
        defaultItemTouchHelper.setDragEnable(true);
        defaultItemTouchHelper.setSwipeEnable(false);
    }

    //图片替换部分
    private void updateImage(final int index) {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                String filesPath = photoList.get(0);
                // 压缩图片
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(filesPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        mAdapter.updateData(outfile, index);
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(getActivity());
    }

    //图片选择部分
    private void selectImage() {
        int maxImgNum = 5 - mAdapter.getList().size();
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                //btnTitlePublish.setBackgroundResource(R.drawable.publish_blue);
                final String[] filesPath = photoList.toArray(new String[photoList.size()]);
                // 压缩图片
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(filesPath).batchAsFile().withOptions(tinyOptions).batchCompress(new FileBatchCallback() {
                    @Override
                    public void callback(boolean isSuccess, String[] outfile) {
                        List<String> outFiles = Arrays.asList(outfile);
                        for (int i = 0; i < outFiles.size(); i++) {
                            int size = mAdapter.getList().size();
                            if (size < 4) {
                                mAdapter.addData(size, outFiles.get(i));
                            } else {
                                mAdapter.appendData(outFiles.get(i));
                            }
                        }
                        LogUtils.d(mAdapter.getList().toString(), TAG);
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(true, maxImgNum)           // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(getActivity());
    }

    //动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    /**
     * RecyclerView Item的触摸事件监听
     */
    private DefaultItemTouchHelperCallback.OnItemTouchCallbackListener mOnItemTouchCallbackListener = new DefaultItemTouchHelperCallback.OnItemTouchCallbackListener() {
        @Override
        public void onSwiped(int adapterPosition) {
            if (mAdapter != null) {
                mAdapter.removeData(adapterPosition);
            }
        }

        @Override
        public boolean onMove(int srcPosition, int targetPosition) {
            if (mAdapter != null) {
                // 更新UI中item的位置
                mAdapter.swapMoved(srcPosition, targetPosition);
            }
            return false;
        }
    };

}
